﻿Function Get-WhiteSpace([string]$server, [string]$MailboxDatabaseName, [array]$WSEvents) {
	$Array = @()
	$Result = @()
	$WSpace = $WSEvents | Where-Object {$_.Message.Contains($MailboxDatabaseName)}
	#$Check = $WSpace -is [array]
	If ($WSpace -is [array]) {
		Write-Verbose ('WSpace is Array?: ' + $($WSpace -is [array]))
		ForEach ($item in $WSpace) {
			$Array = $item.message.split("`"")
			$EndString = $Array[2].indexof("megabytes ")-6
			#Write-Verbose $mbnamearray[1]
			[int]$Result = $Array[2].Substring(5,$EndString)
		}
	} else {
		Write-Verbose ('WSpace is Array?: ' + $($WSpace -is [array]))
		If ($WSpace -ne $null) {
			$Array = $WSpace.message.split("`"")
			$EndString = $Array[2].indexof("megabytes ")-6
			#Write-Verbose $mbnamearray[1]
			[int]$Result = $Array[2].Substring(5,$EndString)
		} else {
			$Result = "No defrag last day"
		}
	}
	$Result
} #end of Function Get-Whitespace

$ServerSkipList = "C:\WINDOWS\Scripts\ExServersToSkip.csv"

$skiplist = @()
Import-Csv $ServerSkipList | ForEach-Object {$skiplist += $_.Servername}


$exchange2007servers = @(Get-MailboxServer | Where-Object {$skiplist -notcontains $_.name} | Sort-Object Name | Select-Object Name) 
$exchange2003servers = @(Get-ExchangeServer | Where-Object {$skiplist -notcontains $_.name -and $_.admindisplayversion.major -ne 8 } | Sort-Object Name | Select-Object Name)
#$exchange2007servers = @(Get-MailboxServer | Where-Object {$_.Name -eq "CHW-MSG-821"} | Sort-Object Name | Select-Object Name) 
#$exchange2003servers = @(Get-ExchangeServer | Where-Object {$_.name -eq "CHW-MSG-301"} | Sort-Object Name | Select-Object Name)
$exchangeServers = $exchange2003servers + $exchange2007servers | Sort
$DatabaseInfo=@()
#---------------8<---------------Function Main Exchange 2007
foreach ($server in $exchangeServers) {
	Write-Verbose "======================"
	$server.name
	$Volumes = Get-WMIObject Win32_Volume -computerName $server.name 
	Write-Verbose "Getting Mailbox Databases"
	$ServerDatabases = Get-MailboxDatabase -Status -server $server.name | Where-Object {$_.Name -ne "Mailbox Database"} | Sort-Object
		If ($ServerDatabases -ne $null) {
			Write-Verbose "Getting 1221 events"
			$GetEventTime = Measure-Command {$WhiteSpaceEvents = Get-EventLog -ComputerName $server.name -log Application -Source "MsExchangeIS Mailbox Store" -EntryType Information -after (get-date).addHours(-36) | Where-Object {$_.EventID -eq 1221 } }
			Write-Verbose ("Time to retrieve events: {0:D2}:{1:D2}" -f $GetEventTime.Minutes,$GetEventTime.Seconds)
			foreach ($MailboxDatabase in $ServerDatabases) {
				$dbdata = "" | Select-Object Servername,DatabaseName,Path,DBSize,Mailboxes,DiskCapacity,FreeOnStorage,PercentFree,Whitespace
	
				Write-Verbose "*****************"
				$DiskCapacity = $null
				$FreeOnStorage = $null
				$FreeOnStoragePercent = $null
				$MDBSize = $null
				$WhiteSpace =$null
				$MBXCount = $null
				$BackupDays = $null
				
				Write-Verbose ("DatabaseName: " + $MailboxDatabase.name)
				$edbfilepath = $MailboxDatabase.edbfilepath.ToString()
				Write-Verbose ('$edbpath: ' + $edbfilepath.ToUpper())
				#convert absolute path to UNC path
				$path = "\\" + $server.name + "\" + $MailboxDatabase.EdbFilePath.PathName.Replace(":","$")
				Write-Verbose ('$path: ' + $path)
				$dbsize = Get-ChildItem $path
				Write-Verbose ('$dbsize: ' + $dbsize)
				
				#$mailboxcount = Get-MailboxStatistics -database "$MailboxDatabase" | measure-object
				$mailboxcount = Get-MailboxDatabase -Server $server.name | where { $_.Name -eq $MailboxDatabase.name } | Get-Mailbox -ResultSize:Unlimited | measure-object
				
				$edbpathlength = 0
				foreach ($volItem in $Volumes) {
					If ( $edbfilepath.ToUpper().startswith($volItem.name.ToUpper()) ) {
						Write-Verbose ($volItem.name.ToUpper() +  "   -   " + $edbfilepath.startswith($volItem.name) +  "   -   " +  $volItem.name.length)			
						If ($edbpathlength -lt $volItem.name.length) {	
							$edbpathlength = $volItem.name.length
							$edbfilepathvolumename = $volItem.name
							$edbfilepathfreespace =  $volItem.freespace
							$edbfilepathcapacity = $volItem.capacity
						}
					}
				}
				
				$VolumeName = $edbfilepathvolumename
				Write-Verbose ('$VolumeName: ' + $VolumeName)
				$FreeOnStorage = "{0:N2}" -f ($edbfilepathfreespace/1GB)
				Write-Verbose ('$DiskCapacity: ' + $DiskCapacity)
				$DiskCapacity = "{0:N2}" -f ($edbfilepathcapacity/1GB)
				Write-Verbose ('$FreeOnStorage: ' + $FreeOnStorage)
				$FreeOnStoragePercent = "{0:P2}" -f ([int] $FreeOnStorage / [int] $DiskCapacity)
				Write-Verbose "FreeOnStoragePercent:  $FreeOnStoragePercent"
				$MDBSize = ("{0:N2}" -f ($dbsize.Length/1GB))
				Write-Verbose ('MDBSize: ' + $MDBSize)
				$WhiteSpace = Get-WhiteSpace $server.name $MailboxDatabase.name $WhiteSpaceEvents
				Write-Verbose ('$WhiteSpace: ' + $WhiteSpace)
			
				$dbdata.Servername = $server.name
				$dbdata.DatabaseName = $MailboxDatabase.name
				$dbdata.Path = $path
				$dbdata.DBSize = $MDBSize
				$dbdata.Mailboxes =  $mailboxcount.count
				$dbdata.DiskCapacity = $DiskCapacity
				$dbdata.FreeOnStorage = $FreeOnStorage
				$dbdata.PercentFree = $FreeOnStoragePercent
				$dbdata.Whitespace = $WhiteSpace
				$DatabaseInfo += $dbdata
			}
		}
		
}  # End of Main Exchange 2007/2003 loop

$DatabaseInfo | Export-Csv -NoTypeInformation ("e:\Reports\DatabaseInfo\ExDatabaseInfo" + $(Get-Date -Format "yyMMdd")+".csv")